<?php
/**
 * Created by PhpStorm.
 * User: 雨寒
 * Date: 2018/8/17
 * Time: 下午2:01
 */

namespace app\common\model;

use think\Cache;
use think\Db;
use think\Exception;

//token加密密钥

class User extends Common
{

    public static function getChargeCount($user_id)
    {
        $user = \db("user")->where("id", $user_id)->find();
        $count = 0;
        if (!empty($user["emailcode"])) {
            $count++;
        }
        if (!empty($user["selfqqcode"])) {
            $count++;
        }
        if (!empty($user["bankcard"])) {
            $count++;
        }
        return $count;
    }

    /**
     * 判断用户是否存在
     *
     * @param string $account 待查询用户的ID或手机号
     * @return array|null 若用户存在则返回用户数组，否则返回null
     */
    static public function exists($account)
    {
        $user = Db::name("user")->where("id|selfphone", "=", $account)->find();
        if(!empty($user)){
            $cardinfo = Db::name("card_apply")->where("user_id", "=", $user['id'])->find();
            if(!empty($cardinfo)){
                $user['selfcard'] = $cardinfo['selfcard'];
                $user['realname'] = $cardinfo['realname'];
            }
        }
        return $user;
    }

    /**
     *  注册用户
     */
    static public function register($nick_name, $mobile, $password, $confirm_password, $sepassword, $parent_mobile = 0)
    {
        //检测用户是否已存在
        if (self::exists($mobile)) {
            throw new UserException("手机号" . $mobile . "已被注册使用！");
        }
        if ($password != $confirm_password) {
            throw new UserException("两次密码不一样！");
        }
        if (empty($sepassword)) {
            throw new UserException("二次密码不能为空！");
        }
        if (!empty($parent_mobile)) {
            
            $parent = \db("user")->where("invite_code", $parent_mobile)->find();
            if (empty($parent)) {
                throw new UserException("没有此推荐人！");
            }
            $parent_id = $parent['id'];
            $rank = $parent["rank"] + 1;
        } else {
//            throw new UserException("请填写推荐人!!");
            $parent_id = 0;
            $rank = 1;
        }

        $nick_name = remove_all_tags($nick_name);
        if (empty($nick_name)) {
            throw new  UserException('请正确输入昵称，避免空格等特殊字符！');
        }
        //判断用户名是否只是有汉字和数字
        // if(!match_chinese($nick_name)){
        //     throw new UserException('请输入合法的昵称，只支持汉字和数字组合');
        // }

        $user_ck = \db("user")->where("username", $nick_name)->find();
        if (!empty($user_ck)) throw new Exception("用户昵称重复");

        $ip = get_client_ip();
        $recently = \db("user")->where("regip", '=', $ip)->order('id desc')->find();
        if (!empty($recently)) {
            $that_date = strtotime($recently['regtime']);
            $that_time = (time() - $that_date);
            if ($that_time < config("setting.recentlysecond")) {
                throw new  UserException('注册过快，休息一下吧！');
            }
        }
        //用户信息
        $user = array(
            'selfphone' => $mobile,
            'pid' => $parent_id,
            'username' => $nick_name,
            'passwd' => encrypt_user_password($password),
            'regtime' => date("Y-m-d H:i:s", now_datetime()),
            'regip' => $ip,
            "levelid" => 1,
            "is_active" => 1,
            "integral" => config("setting.register_score"),
            "sepasswd" => encrypt_user_password($sepassword),
            "rank" => $rank,
            "invite_code"=>getInviteCode()
        );
        if (!empty($parent)) {
            $user['recommend'] = $parent["recommend"] . "," . $parent_id . ",";
        }

        //创建用户
        $result = Db::name("user")->insertGetId($user);
        //添加共享豆赠送记录
        points_his($result, 1, 5, 0, '注册赠送共享豆');

        if (empty($result)) {
            throw new ServerException("创建新用户失败！数据库" . __FILE__ . __LINE__);
        }
        //返回用户uid
        return $result;
    }


    /**
     * 登录用户
     */
    static public function login($mobile, $password)
    {
        if (empty($password)) {
            throw new UserException("请填写密码或者验证码！");
        }
        //查找用户
        $user = self::exists($mobile);

        //判断用户存在性
        if (!$user) {
            throw new UserException("用户【" . $mobile . "】不存在！");
        }

        /*密码登录*/
        if (!empty($password)) {
            //判断密码是否正确
            if (encrypt_user_password($password) != $user["passwd"]) {
                throw new UserException("登录密码错误！");
            }
        }

        //判断是否被拉黑
        if ($user["is_active"] != 1) {
            throw new UserException("您的账号已被拉黑，请及时联系管理员处理！");
        }

        //添加登录记录
        db("userlogin")->insert([
            "date" => now_datetime(),
            "ip" => get_client_ip(),
            "user" => $mobile
        ]);
        //返回token
        return array(
            "uid" => $user["id"],
        );
    }


    /**
     * 修改密码
     */
    static public function changePassword($user, $oldpassword, $newpassword, $confirmpassword)
    {

        //判断旧密码对不对
        if (encrypt_user_password($oldpassword) != $user["password"]) {
            throw new UserException("旧密码错误！");
        }

        //新密码与确认密码是否一致
        if ($confirmpassword != $newpassword) {
            throw new UserException("新密码与确认密码不一致！");
        }

        //新密码是否未改变
        if ($oldpassword == $newpassword) {
            throw new UserException("新密码不能与旧密码相同！");
        }

        //修改密码
        $result = Db::name("user")
            ->where("id", $user["id"])
            ->setField("password", encrypt_user_password($newpassword));
        if ($result) {
        } else {
            throw new ServerException('密码未能保存');
        }
        return '新密码设置成功！';
    }

    /**
     * 忘记密码重新设置密码
     */

    static public function forgetPassword($mobile, $newpassword, $confirmpassword)
    {
        //判断用户是否存在
        $user = User::exists($mobile);

        //判断确认密码是否相同
        if ($newpassword != $confirmpassword) {
            throw new UserException("请重新填写确认密码!");
        }
        //判断用户存在性
        if (!$user) {
            throw new UserException("手机号【" . $mobile . "】未注册！");
        }

        $oldpassword = $user['password'];
        if ($oldpassword == encrypt_user_password($newpassword)) {
            throw new UserException("新密码不能与旧密码一致！");
        }
        //修改密码
        $result = Db::name("user")
            ->where("id", $user["id"])
            ->setField("password", encrypt_user_password($newpassword));

        if ($result) {
        } else {
            throw new ServerException('密码未能保存');
        }
        return '新密码设置成功！';
    }

    public static function getProCity($item)
    {
        return \db("region")->where("id_path", "1-" . $item['pro_id'] . "-" . $item["city_id"] . "-" . $item["area_id"])->value("name_path");
    }


    /**
     * 校验用户是否已经激活，个人基本信息是否已经完善
     * @param $user_id
     * @throws Exception
     */
    public static function verifyUser($user_id)
    {
        if (empty($user_id)) {
            throw new Exception("参数异常");
        }

        $userinfo = self::exists($user_id);
        if ($userinfo["user_status"] != 1) {
            throw new Exception("需推荐人或任意上级转账" . config("setting.transpoint") . "共享豆激活");
        }
        $pay_num = 0;
        if (empty($userinfo['emailname']) || empty($userinfo['email']) || empty($userinfo['emailcode'])) {
            $pay_num = ($pay_num + 1);
            //支付宝未完善
        }
        if (empty($userinfo['realname']) || empty($userinfo['banktypename']) || empty($userinfo['bankname']) || empty($userinfo['bankcard'])) {
            $pay_num = ($pay_num + 1);
            //银行卡未完善
        }
        if (empty($userinfo['selfqqname']) || empty($userinfo['selfqq']) || empty($userinfo['selfqqcode'])) {
            $pay_num = ($pay_num + 1);
            //微信支付未完善
        }
        if ($pay_num == 3) {
            throw new Exception("最少需要完善一项收款方式");
        }
        if ($userinfo['selfcard'] <> '' && $userinfo['realname'] <> '' && $userinfo['mustman'] <> '') {
        } else {
            throw new Exception("请先完成实名认证");
        }
        return $userinfo;
    }

    /**
     * 用户等级信息
     * @param $user_id
     * @return string
     */
    static public function thatlevel($id)
    {
        $title = Db::name('userlevel')->where("id='" . $id . "'")->field('title')->find();
        $title = empty($title) ? '等级已删除' : $title['title'];
        return $title;
    }


    /*
     * 实名认证
     * */
    static public function verify_name($data)
    {
        $uid = session("user_id");
        if (empty($uid)) {
            $ary = array('s' => 1, 'msg' => '请先登录！');
            return json_encode($ary);
        }
        if (empty($data['realname'])) {
            $ary = array('s' => 2, 'msg' => '请填写真实姓名！');
            return json_encode($ary);
        }
        if (empty($data['selfcard'])) {
            $ary = array('s' => 2, 'msg' => '请填写证件号码！');
            return json_encode($ary);
        }
        if (empty($data['mustman'])) {
            $ary = array('s' => 2, 'msg' => '请填写紧急联系人电话！');
            return json_encode($ary);
        }
        // if (empty($data['pwd'])) {
        //     $ary = array('s' => 3, 'msg' => '请填写交易密码！');
        //     return json_encode($ary);
        // }


        $userdata['selfcard'] = htmlspecialchars(trim($data['selfcard']));
        $userdata['mustman'] = htmlspecialchars(trim($data['mustman']));
        $userdata['card_1'] = htmlspecialchars($data['card_1']);
        $userdata['card_2'] = htmlspecialchars($data['card_2']);

        $code_istrue = validate_ind($userdata['selfcard']);
        if (!$code_istrue) {
            $ary = array('s' => 3, 'msg' => '请正确填写身份证号！');
        }


        $userinfo = userallinfo($uid);
        // if (md5(md5($data['pwd'])) == $userinfo['sepasswd']) {

            $userdata['realname'] = htmlspecialchars(trim($data['realname']));
//            Db::name('user')->where(['id' => $uid])->update($userdata);//realname  selfcard
            $apply = \db("card_apply")->where("user_id", $uid)->where("status", '<', 2)->find();
            if ($apply) {
                $ary = array('s' => 10, 'msg' => '实名认证已提交！');
                return json_encode($ary);
            } else {
                $r = \db('card_apply')->insert([
                    'user_id'=>$uid,
                    'realname'=>$userdata['realname'],
                    'selfcard'=>$userdata['selfcard'],
                    'mustman'=>$userdata['mustman'],
                    'card_1'=>$userdata['card_1'],
                    'card_2'=>$userdata['card_2'],
                    'status'=>0,
                    'create_time'=>time()
                ]);
                if($r){
                    $ary = array('s' => 10, 'msg' => '实名认证提交成功！');
                }else{
                    $ary = array('s' => 4, 'msg' => '系统繁忙，请稍后再试！');
                }
                return json_encode($ary);
            }
        // } else {
        //     $ary = array('s' => 5, 'msg' => '密码错误，请检查输入！');
        //     return json_encode($ary);
        // }
    }

    /*
     * 检测用户的支付宝  微信  银行卡号是否都完善
     * */
    static public function paycodeimg()
    {
        $uid = session("user_id");
        $userinfo = userallinfo($uid);
        /*支付宝是否绑定判断*/
        if (empty($userinfo['emailname']) || empty($userinfo['email']) || empty($userinfo['emailcode'])) {
            /*没有认证完成支付宝*/
            $alipay = ['status' => 1, 'url' => url('Paytype/pay_alipay')];
        } else {
            $alipay = ['status' => 2, 'url' => url('Paytype/pay_alipay')];
        }
        /*微信是否绑定判断*/
        if (empty($userinfo['selfqqname']) || empty($userinfo['selfqq']) || empty($userinfo['selfqqcode'])) {
            /*没有认证完成微信*/
            $wechat = ['status' => 1, 'url' => url('Paytype/pay_wechat')];
        } else {
            $wechat = ['status' => 2, 'url' => url('Paytype/pay_wechat')];
        }

        /*银行卡号是否绑定判断*/
        if (empty($userinfo['realname']) || empty($userinfo['banktypename']) || empty($userinfo['bankname']) || empty($userinfo['bankcard'])) {
            /*没有认证完成银行卡号*/
            $card = ['status' => 1, 'url' => url('Paytype/pay_card')];
        } else {
            $card = ['status' => 2, 'url' => url('Paytype/pay_card')];
        }
        return [$alipay, $wechat, $card];
    }

    /**
     * 转赠共享豆
     * @param $post
     * @return array
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public static function transpoint($post)
    {
        $_POST = $post;
        $uid = session("user_id");
        $userinfo = userallinfo($uid);
        if (empty($uid)) {
            return $ary = array('s' => 2, 'msg' => '请您先登录！');
        }
        $num = intval($post['num']);
        if ($num <= 0) {
            return $ary = array('s' => 2, 'msg' => '非法操作！');
        }

        /*再检查手机号对应账号是不是一条线上的，那就找到那个人的pidstr*/
        $pidstr = db('user')->where('selfphone="' . trim($_POST['tel']) . '"')->find();

        if (empty($pidstr['id'])) {
            return $ary = array('s' => 2, 'msg' => '该手机号尚未注册平台！');
        }
        if ($uid == $pidstr['id']) {
            return $ary = array('s' => 2, 'msg' => '无法转增给自己！');
        }
        $pid_ary = trans_pidstr($pidstr['recommend']);
        if (empty($pid_ary)) {
            return $ary = array('s' => 2, 'msg' => '该账号无推荐人，请联系管理员后台激活！');
        }
        if (!in_array($uid, $pid_ary)) {
            return $ary = array('s' => 2, 'msg' => '该账号和您不在同一个团队，无法转增！');
        }
        /*查看共享豆是否足够*/
        if ($num > $userinfo['integral']) {
            return $ary = array('s' => 2, 'msg' => '余额不足，无法转增！');
        }
        /*1.减掉自己余额  2加上对方余额-30  3.双方共享豆记录一下,最后激活对方账号*/
        if ($pidstr['user_status'] == 0) {
            if ($num < config("setting.transpoint")) {
                return $ary = array('s' => 2, 'msg' => '激活时转增数量不得低于' . config("setting.transpoint") . '个！');
            }
            if ($num >= config("setting.transpoint")) {
                $can_get_intergral = $num;
                $data_other['integral'] = ($pidstr['integral'] + $can_get_intergral);
                $data_other['user_status'] = 1;
                $data_other['activemanuid'] = $uid;
                \db('user')->where('id="' . $pidstr['id'] . '"')->update($data_other);
                points_his($pidstr['id'], 1, $can_get_intergral, $userinfo['id'], $userinfo['selfphone'] . '赠送');

                /*====给上一级的直推人数加1，以及上一级的每一个人团队人数加一======start===*/
                //先找到上一级的id，以及上一级的全部路径
                $this_active_parentid = $pidstr['pid'];
                if (!empty($this_active_parentid)) {
                    $myupinfo = \db('user')->where("id='" . $this_active_parentid . "'")->field('id,pid,pidcount,recommend,teamcount')->find();
                    //先给上一级直推人数加一
                    \db('user')->where("id='" . $this_active_parentid . "'")->setInc('pidcount');
                    $ary_up = excommend($pidstr['recommend']);
                    /*再给每一个上一级团队人数加1*/
                    foreach ($ary_up as $teamv) {
                        \db('user')->where("id='" . $teamv . "'")->setInc('teamcount');
                        //检测每一个人当前级别，检测到了就存进去
                        $thislev = \db('user')->where("id='" . $teamv . "'")->field('id,pidcount,teamcount,pushs,is_levfix')->find();
                        if ($thislev['is_levfix'] != 2) {
                            //查询出售的收益
                            $now_point_str = "uid='" . $thislev['id'] . "' and isadd=2 and info='资产出售'";
                            $now_user_points = \db("Pushslist")->where($now_point_str)->sum('nums');
                            $now_user_points = empty($now_user_points) ? 0 : $now_user_points;
                            $thislev['pushs'] = ($thislev['pushs'] + $now_user_points);
                            if ($thislev['pidcount']>=config('team_config.level_4')['pidcount'] && $thislev['teamcount']>=config('team_config.level_4')['teamcount'] && $thislev['pushs']>=config('team_config.level_4')['pushs']) {
                                $thisdata['levelid'] = 4;//三级代理
                            } else if ($thislev['pidcount']>=config('team_config.level_3')['pidcount'] && $thislev['teamcount']>=config('team_config.level_3')['teamcount'] && $thislev['pushs']>=config('team_config.level_3')['pushs']) {
                                $thisdata['levelid'] = 3;//二级代理
                            } else if ($thislev['pidcount']>=config('team_config.level_2')['pidcount'] && $thislev['teamcount']>=config('team_config.level_2')['teamcount'] && $thislev['pushs']>=config('team_config.level_2')['pushs']) {
                                $thisdata['levelid'] = 2;//一级代理
                            } else {
                                $thisdata['levelid'] = 1;//普通会员
                            }
                            \db('User')->where("id='" . $teamv . "'")->update($thisdata);
                        }
                    }
                }
                /*====给上一级的直推人数加1，以及上一级的每一个人团队人数加一======end===*/
            }
        } else {
            if ($num < config("setting.transpoint")) {
                return $ary = array('s' => 2, 'msg' => '转赠数量不得低于' . config("setting.transpoint") . '个！');
            }
            $data_other['integral'] = ($pidstr['integral'] + $num);
            \db('user')->where('selfphone="' . trim($_POST['tel']) . '"')->update($data_other);
            points_his($pidstr['id'], 1, $num, $userinfo['id'], $userinfo['selfphone'] . '赠送');
        }
        $data_us['integral'] = ($userinfo['integral'] - $post['num']);
        \db('user')->where('id="' . trim($userinfo['id']) . '"')->update($data_us);
        points_his($userinfo['id'], 2, $post['num'], 0, '赠送给' . $post['tel']);
        return $ary = array('s' => 10, 'msg' => '转增成功！');
    }

    /*
     * 查看用户是否完成实名认证，是否填写收款信息，是否激活币激活
     * */
    static public function activestatus($userinfo = '')
    {
        if (empty($userinfo)) {
            $uid = session("user_id");
            $userinfo = self::exists($uid);
        }

        if ($userinfo['user_status'] == 0) {
            return array('code' => 1001, 'msg' => '需推荐人或任意上级转账' . config("setting.transpoint") . '共享豆激活！', 'img' => '1.png');
        }
        $pay_num = 0;
        if (empty($userinfo['emailname']) || empty($userinfo['email']) || empty($userinfo['emailcode'])) {
            $pay_num = ($pay_num + 1);
            //支付宝未完善
        }
        if (empty($userinfo['realname']) || empty($userinfo['banktypename']) || empty($userinfo['bankname']) || empty($userinfo['bankcard'])) {
            $pay_num = ($pay_num + 1);
            //银行卡未完善
        }
        if (empty($userinfo['selfqqname']) || empty($userinfo['selfqq']) || empty($userinfo['selfqqcode'])) {
            $pay_num = ($pay_num + 1);
            //微信支付未完善
        }
        if ($pay_num == 3) {
            return array('code' => 1002, 'msg' => '最少需要完善一项收款方式！', 'img' => '1.png');
        }
       
        if ($userinfo['selfcard'] <> '' && $userinfo['realname'] <> '' && $userinfo['mustman'] <> '') {
        } else {
            return array('code' => 1003, 'msg' => '请先完成实名认证！', 'img' => '1.png');
        }
        return array('code' => 1000, 'msg' => 'ok');
    }
}
